<template>
    <div class="page-container">
        <div class="button-group">
            <el-button icon="el-icon-back" @click="$router.push('/main/renshi/jixiao')">返回</el-button>
            <span>
                <el-button type="primary" icon="el-icon-check" @click="saveForm" v-if="!isView">保存</el-button>
                <el-button type="success" icon="el-icon-menu" @click="goToList">查看列表</el-button>
                <el-button type="info" icon="el-icon-printer" @click="printForm">打印表单</el-button>
            </span>
        </div>


        <div class="form-container">
            <h2>职员绩效薪资核定表</h2>
            <div class="basic-info">
                <el-form :model="formData" label-width="100px">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="姓名">
                                <el-input v-model="formData.name" :disabled="isView" placeholder="请输入姓名"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="工号">
                                <el-input v-model="formData.employeeId" :disabled="isView"
                                    placeholder="请输入工号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="入职日期">
                                <el-date-picker v-model="formData.entryDate" type="date" :disabled="isView"
                                    :picker-options="datePickerOptions" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                                    placeholder="选择日期" @change="handleDateChange('entryDate')" style="width: 100%">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="拟派部门">
                                <el-input v-model="formData.department" :disabled="isView"
                                    placeholder="请输入部门"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="拟派职位">
                                <el-input v-model="formData.position" :disabled="isView" placeholder="请输入职位"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="职等职级">
                                <el-input v-model="formData.probationGrade" :disabled="isView"
                                    placeholder="请输入职级"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <div class="salary-section">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="salary-card probation">
                            <div class="card-header">试用期内核计薪资</div>
                            <el-form :model="formData" label-width="120px">
                                <el-form-item label="绩效工资">
                                    <el-input-number v-model="formData.probationPerformancePay" :disabled="isView"
                                        :controls="false" :precision="2"></el-input-number>
                                </el-form-item>
                                <el-form-item label="工龄">
                                    <el-input-number v-model="formData.probationSeniority" :disabled="isView"
                                        :controls="false" :precision="2"></el-input-number>
                                </el-form-item>
                                <el-form-item label="岗位特殊津贴">
                                    <el-input-number v-model="formData.probationSpecialAllowance" :disabled="isView"
                                        :controls="false" :precision="2"></el-input-number>
                                </el-form-item>
                                <el-form-item label="绩效奖金(KPI)">
                                    <el-input-number v-model="formData.probationKpiBonus" :disabled="isView"
                                        :controls="false" :precision="2"></el-input-number>
                                </el-form-item>
                                <el-form-item label="特殊说明">
                                    <el-input type="textarea" v-model="formData.probationSpecialNote" :disabled="isView"
                                        :rows="3"></el-input>
                                </el-form-item>
                                <el-form-item label="合计薪资">
                                    <div class="total-salary">{{ calculateProbationTotal() }}</div>
                                </el-form-item>
                            </el-form>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="salary-card regular">
                            <div class="card-header">转正后核计薪资</div>
                            <el-form :model="formData" label-width="120px">
                                <el-form-item label="绩效工资">
                                    <el-input-number v-model="formData.regularPerformancePay" :disabled="isView"
                                        :controls="false" :precision="2"></el-input-number>
                                </el-form-item>
                                <el-form-item label="工龄">
                                    <el-input-number v-model="formData.regularSeniority" :disabled="isView"
                                        :controls="false" :precision="2"></el-input-number>
                                </el-form-item>
                                <el-form-item label="岗位特殊津贴">
                                    <el-input-number v-model="formData.regularSpecialAllowance" :disabled="isView"
                                        :controls="false" :precision="2"></el-input-number>
                                </el-form-item>
                                <el-form-item label="绩效奖金(KPI)">
                                    <el-input-number v-model="formData.regularKpiBonus" :disabled="isView"
                                        :controls="false" :precision="2"></el-input-number>
                                </el-form-item>
                                <el-form-item label="特殊说明">
                                    <el-input type="textarea" v-model="formData.regularSpecialNote" :disabled="isView"
                                        :rows="3"></el-input>
                                </el-form-item>
                                <el-form-item label="合计薪资">
                                    <div class="total-salary">{{ calculateRegularTotal() }}</div>
                                </el-form-item>
                            </el-form>
                        </div>
                    </el-col>
                </el-row>
            </div>

            <div class="approval-section">
                <el-form :model="formData" label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="薪资面谈人">
                                <el-input v-model="formData.salaryInterviewer" :disabled="isView"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="人资经办">
                                <el-input v-model="formData.hrOperator" :disabled="isView"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="用人单位经理">
                                <el-input v-model="formData.departmentManager" :disabled="isView"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="部长/总监">
                                <el-input v-model="formData.departmentDirector" :disabled="isView"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <div class="notice">
                申明：本人对以上薪资核定无任何异议，并同意公司按制度核定我的绩效薪资！
            </div>

            <div class="signature-section">
                <el-form :model="formData" label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="应征者签名">
                                <el-input v-model="formData.applicantSignature" :disabled="isView"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="日期">
                                <el-date-picker v-model="formData.applicantDate" type="date" :disabled="isView"
                                    :picker-options="datePickerOptions" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                                    @change="handleDateChange('applicantDate')" style="width: 100%">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="总裁/董事长">
                                <el-input v-model="formData.presidentSignature" :disabled="isView"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="企业管理部">
                                <el-input v-model="formData.corporateManagementSignature" :disabled="isView"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="总经理">
                                <el-input v-model="formData.generalManagerSignature" :disabled="isView"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <div class="process-description">
                表单运作流程：人资面谈建议性工资 → 部门经理复核 → 部长/总监核实 → 总经理审核 → 企业管理部复核 → 总裁批准
            </div>
            <div class="form-footer">
                <span>表单编号及版本：AM - JY - 017 A/2</span> <span>保存期限：长期</span>
            </div>
        </div>
    </div>
</template>

<script>
import { getPerformanceDetail, createPerformance, updatePerformance } from '@/api/performance'
// import html2pdf from 'html2pdf.js'
import { formatDateTime, formatDate } from '@/utils/date'

export default {
    data() {
        return {
            formData: {
                id: null,
                name: '',
                employeeId: '',
                entryDate: '',
                department: '',
                position: '',
                probationGrade: '',
                regularGrade: '',
                probationPerformancePay: 0,
                probationSeniority: 0,
                probationSpecialAllowance: 0,
                probationKpiBonus: 0,
                probationSpecialNote: '',
                regularPerformancePay: 0,
                regularSeniority: 0,
                regularSpecialAllowance: 0,
                regularKpiBonus: 0,
                regularSpecialNote: '',
                salaryInterviewer: '',
                hrOperator: '',
                departmentManager: '',
                departmentDirector: '',
                applicantSignature: '',
                applicantDate: '',
                presidentSignature: '',
                corporateManagementSignature: '',
                generalManagerSignature: ''
            },
            isView: false,
            isEdit: false,
            datePickerOptions: {
                shortcuts: [
                    {
                        text: '今天',
                        onClick(picker) {
                            const date = new Date();
                            picker.$emit('pick', formatDate(date));
                        }
                    },
                    {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', formatDate(date));
                        }
                    },
                    {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', formatDate(date));
                        }
                    },
                    {
                        text: '一个月前',
                        onClick(picker) {
                            const date = new Date();
                            date.setMonth(date.getMonth() - 1);
                            picker.$emit('pick', formatDate(date));
                        }
                    },
                    {
                        text: '三个月前',
                        onClick(picker) {
                            const date = new Date();
                            date.setMonth(date.getMonth() - 3);
                            picker.$emit('pick', formatDate(date));
                        }
                    }
                ]
            }
        };
    },
    created() {
        const id = this.$route.query.id;
        const type = this.$route.query.type;

        if (id) {
            this.isEdit = type === 'edit';
            this.isView = type === 'view';
            this.fetchData(id);
        }
    },
    methods: {
        async fetchData(id) {
            try {
                const response = await getPerformanceDetail(id);
                if (response.data) {
                    const data = response.data;
                    // 格式化日期
                    data.entryDate = data.entryDate ? formatDate(new Date(data.entryDate)) : '';
                    data.applicantDate = data.applicantDate ? formatDate(new Date(data.applicantDate)) : '';
                    this.formData = data;
                }
            } catch (error) {
                this.$message.error('获取数据失败：' + error.message);
            }
        },
        async saveForm() {
            try {
                // 表单验证
                if (!this.formData.entryDate) {
                    this.$message.warning('请选择入职日期');
                    return;
                }

                let formDataToSubmit = { ...this.formData };

                // 处理日期格式
                try {
                    // 入职日期处理
                    if (formDataToSubmit.entryDate) {
                        const entryDate = new Date(formDataToSubmit.entryDate);
                        if (isNaN(entryDate.getTime())) {
                            this.$message.warning('入职日期格式不正确');
                            return;
                        }
                        formDataToSubmit.entryDate = formatDate(entryDate);
                    }

                    // 申请日期处理
                    if (formDataToSubmit.applicantDate) {
                        const applicantDate = new Date(formDataToSubmit.applicantDate);
                        if (isNaN(applicantDate.getTime())) {
                            this.$message.warning('申请日期格式不正确');
                            return;
                        }
                        formDataToSubmit.applicantDate = formatDate(applicantDate);
                    } else {
                        // 如果没有申请日期，默认使用当前日期
                        formDataToSubmit.applicantDate = formatDate(new Date());
                    }
                } catch (error) {
                    this.$message.error('日期格式化失败：' + error.message);
                    return;
                }

                let response;
                if (formDataToSubmit.id) {
                    response = await updatePerformance(formDataToSubmit.id, formDataToSubmit);
                } else {
                    response = await createPerformance(formDataToSubmit);
                }

                if (response.data) {
                    this.$message.success('保存成功');
                    this.goToList();
                }
            } catch (error) {
                this.$message.error('保存失败：' + error.message);
            }
        },
        goToList() {
            this.$router.push('/main/biao/jixiaoxz-list').catch(err => {
                if (err.name !== 'NavigationDuplicated') {
                    throw err;
                }
            });
        },
        calculateProbationTotal() {
            return (
                parseFloat(this.formData.probationPerformancePay || 0) +
                parseFloat(this.formData.probationSeniority || 0) +
                parseFloat(this.formData.probationSpecialAllowance || 0) +
                parseFloat(this.formData.probationKpiBonus || 0)
            ).toFixed(2);
        },
        calculateRegularTotal() {
            return (
                parseFloat(this.formData.regularPerformancePay || 0) +
                parseFloat(this.formData.regularSeniority || 0) +
                parseFloat(this.formData.regularSpecialAllowance || 0) +
                parseFloat(this.formData.regularKpiBonus || 0)
            ).toFixed(2);
        },
        handleDateChange(field) {
            if (this.formData[field]) {
                // 使用 formatDate 格式化日期
                const date = new Date(this.formData[field]);
                if (!isNaN(date.getTime())) {
                    this.formData[field] = formatDate(date);
                }
            }
        },
        // downloadPDF() {
        //     // 显示加载提示
        //     const loading = this.$loading({
        //         lock: true,
        //         text: '正在生成PDF，请稍候...',
        //         spinner: 'el-icon-loading',
        //         background: 'rgba(255, 255, 255, 0.7)'
        //     });

        //     // 隐藏不需要打印的元素
        //     const buttonGroup = document.querySelector('.button-group');
        //     buttonGroup.style.display = 'none';

        //     // PDF配置选项
        //     const pdfOptions = {
        //         margin: [10, 10],
        //         filename: `职员绩效薪资核定表_${this.formData.name || '未命名'}_${this.formatDate(new Date())}.pdf`,
        //         image: { type: 'jpeg', quality: 0.98 },
        //         html2canvas: { 
        //             scale: 2,
        //             useCORS: true,
        //             logging: false
        //         },
        //         jsPDF: { 
        //             unit: 'mm', 
        //             format: 'a4', 
        //             orientation: 'portrait' 
        //         }
        //     };

        //     // 获取要导出的内容
        //     const element = document.querySelector('.form-container');

        //     // 生成PDF
        //     html2pdf().set(pdfOptions).from(element).save().then(() => {
        //         // 恢复隐藏的元素
        //         buttonGroup.style.display = 'flex';
        //         // 关闭加载提示
        //         loading.close();
        //         // 显示成功提示
        //         this.$message.success('PDF文件已生成');
        //     }).catch(error => {
        //         // 恢复隐藏的元素
        //         buttonGroup.style.display = 'flex';
        //         // 关闭加载提示
        //         loading.close();
        //         // 显示错误提示
        //         this.$message.error('生成PDF失败：' + error.message);
        //     });
        // },
        printForm() {
            // 显示加载提示
            const loading = this.$loading({
                lock: true,
                text: '正在准备打印...',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 0.7)'
            });

            // 保存当前页面滚动位置
            const scrollPos = window.scrollY;

            // 创建打印样式
            const style = document.createElement('style');
            style.type = 'text/css';
            style.innerHTML = `
                @media print {
                    body * {
                        visibility: hidden;
                    }
                    .form-container, .form-container * {
                        visibility: visible;
                    }
                    .form-container {
                        position: absolute;
                        left: -40px;
                        top: 0;
                        width: 250mm;
                        padding: 10mm;
                        box-sizing: border-box;
                        box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
                    }
                        .salary-section {
    margin-bottom: 15px !important;
}
                    .button-group {
                        display: none !important;
                    }
                    .basic-info,
                    .salary-section .salary-card,
                    .approval-section,
                    .signature-section {
                        break-inside: avoid;
                        page-break-inside: avoid;
                        border: 1px solid #dcdfe6;
                        margin-bottom: 5mm;
                        background-color: white !important;
                    }
                    .salary-section {
                        break-inside: avoid;
                        page-break-inside: avoid;
                    }
                    .notice {
                        break-inside: avoid;
                        page-break-inside: avoid;
                        border: 0px solid #e6a23c;
                        background-color: white !important;
                    }
                    .process-description,
                    .form-footer {
                        break-inside: avoid;
                        page-break-inside: avoid;
                    }
                    h2 {
                        margin-top: 0;
                    }
                    .total-salary {
                        color: #f56c6c !important;
                    }
                    .card-header {
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }
                }
            `;

            // 添加打印样式到头部
            document.head.appendChild(style);

            // 关闭加载提示
            loading.close();

            // 调用打印
            setTimeout(() => {
                window.print();

                // 打印完成后移除样式
                setTimeout(() => {
                    document.head.removeChild(style);
                    // 恢复滚动位置
                    window.scrollTo(0, scrollPos);
                }, 100);
            }, 300);
        }
    }
};
</script>

<style lang="scss" scoped>
.page-container {
    min-height: calc(100vh - 48px);
    padding: 32px;
    // background: linear-gradient(to bottom, #f8f9fa, #ffffff);
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    @media screen and (max-width: 768px) {
        padding: 16px;
    }
}

.button-group {
    width: 1200px;
    margin: 0 auto;
    // position: sticky;
    // top: 0;
    z-index: 10;
    display: flex;
    gap: 12px;
    margin-bottom: 24px;
    padding: 16px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-between;


    .el-button {
        padding: 12px 24px;
        font-weight: 500;
        transition: all 0.3s ease;

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        i {
            margin-right: 8px;
        }
    }

    @media screen and (max-width: 768px) {
        flex-direction: column;
        position: static;

        .el-button {
            width: 100%;
        }
    }
}

h2 {
    text-align: center;
    color: #2c3e50;
    font-size: 28px;
    // margin: 32px 0;
    font-weight: 600;
    letter-spacing: 1px;

    @media screen and (max-width: 768px) {
        font-size: 24px;
        margin: 24px 0;
    }
}

.form-container {
    width: 1165px;
    margin: 0 auto;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);
    padding: 32px;

    @media screen and (max-width: 768px) {
        padding: 16px;
    }
}

.basic-info {
    background: #f8f9fa;
    padding: 24px;
    border-radius: 8px;
    margin-bottom: 32px;
    border: 1px solid #e9ecef;
}

.salary-section {
    margin-bottom: 32px;

    .salary-card {
        background: #ffffff;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        padding: 24px;
        height: 100%;
        border: 1px solid #e9ecef;

        .card-header {
            font-size: 18px;
            font-weight: 600;
            color: #ffffff;
            padding: 16px 20px;
            border-radius: 8px;
            margin-bottom: 24px;
            text-align: center;
            letter-spacing: 1px;
        }

        &.probation .card-header {
            background: linear-gradient(135deg, #409EFF, #3a8ee6);
        }

        &.regular .card-header {
            background: linear-gradient(135deg, #67C23A, #5daf34);
        }

        .el-form-item {
            margin-bottom: 20px;
        }
    }

    .total-salary {
        font-size: 20px;
        font-weight: 600;
        color: #f56c6c;
        text-align: right;
        padding: 12px 16px;
        background: #fff5f5;
        border-radius: 6px;
        margin-top: 16px;
    }
}

.approval-section {
    background: #f8f9fa;
    padding: 24px;
    border-radius: 8px;
    margin-bottom: 32px;
    border: 1px solid #e9ecef;
}

.notice {
    background: #fdf6ec;
    color: #e6a23c;
    padding: 20px;
    border-radius: 8px;
    margin: 32px 0;
    font-size: 15px;
    line-height: 1.6;
    text-align: center;
    border: 1px solid #faecd8;
}

.signature-section {
    background: #f8f9fa;
    padding: 24px;
    border-radius: 8px;
    margin-bottom: 32px;
    border: 1px solid #e9ecef;
}

.process-description {
    color: #606266;
    font-size: 14px;
    text-align: center;
    margin: 32px 0;
    line-height: 1.8;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px dashed #dcdfe6;
}

.form-footer {
    display: flex;
    justify-content: space-between;
    text-align: center;
    color: #909399;
    font-size: 13px;
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
}

:deep(.el-input),
:deep(.el-input-number) {
    width: 100%;

    .el-input__inner {
        border-radius: 4px;

        &:hover {
            border-color: #c0c4cc;
        }

        &:focus {
            border-color: #409EFF;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
        }
    }
}

:deep(.el-date-editor) {
    width: 100% !important;
}

/* 响应式布局优化 */
@media screen and (max-width: 768px) {
    .el-row {
        margin-left: 0 !important;
        margin-right: 0 !important;
    }

    .el-col {
        padding-left: 0 !important;
        padding-right: 0 !important;
    }

    .salary-section {
        .salary-card {
            margin-bottom: 20px;
        }
    }
}

/* 打印样式优化 */
@media print {
    .page-container {
        padding: 0;
        background: white;
    }

    .salary-section {
        margin-bottom: 15px !important;
    }

    .button-group {
        display: none !important;
    }

    .form-container {
        box-shadow: none;
        // padding: 20mm;
        max-width: none;
    }

    .basic-info,
    .salary-section .salary-card,
    .approval-section,
    .signature-section {
        break-inside: avoid;
        page-break-inside: avoid;
        border: 1px solid #dcdfe6;
        margin-bottom: 5mm;
        background-color: white !important;
    }

    .salary-section {
        break-inside: avoid;
        page-break-inside: avoid;

        .salary-card {
            .card-header {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        }
    }

    .notice {
        break-inside: avoid;
        page-break-inside: avoid;
        border: 0px solid #e6a23c;
        margin: 5mm 0;
    }

    .process-description,
    .form-footer {
        break-inside: avoid;
        page-break-inside: avoid;
        margin: 5mm 0;
        border: none;
        width: 80%;
    }

    ::v-deep .el-input__inner {
        border: none !important;
    }

    ::v-deep .el-textarea__inner {
        border: none !important;
        resize: none;
    }
}

:deep(.el-date-picker) {
    .el-picker-panel__content {
        .el-date-picker__header {
            margin: 10px;
            text-align: center;

            .el-picker-panel__icon-btn {
                font-size: 16px;
                color: #409EFF;
            }
        }

        .el-date-picker__header-label {
            font-size: 16px;
            font-weight: 500;
        }

        .el-picker-panel__content {
            margin: 15px;

            .el-date-table {
                th {
                    padding: 5px;
                    color: #606266;
                }

                td {
                    padding: 0;
                    height: 32px;

                    &.current:not(.disabled) .el-date-table-cell__text {
                        color: #fff;
                        background-color: #409EFF;
                    }

                    &:hover {
                        .el-date-table-cell__text {
                            background-color: #ecf5ff;
                        }
                    }
                }
            }
        }
    }
}
</style>